package com.effectiv.gooruda.business.api;

import java.io.Serializable;
import javax.annotation.PostConstruct;
import jodd.bean.BeanUtil;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.mapping.event.AbstractMongoEventListener;
import org.springframework.data.mongodb.repository.MongoRepository;
import com.effectiv.gooruda.domain.Tenant;
import com.effectiv.gooruda.security.SecurityUtil;
import com.google.common.eventbus.EventBus;

@Slf4j
public abstract class AbstractBusinessService<T, Id extends Serializable>
		extends AbstractMongoEventListener<T> implements
		BusinsessService<T, Id> {

	@Autowired
	@Getter
	private MongoTemplate template;
	@Autowired
	private EventBus bus;

	@Getter
	@Setter
	private MongoRepository repository;

	
	private final String TENANT = "tenant";
	

	protected void post(Object event) {
		if (event != null) {
			bus.post(event);
		}
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public T update(T t) {
		
		return (T) repository.save(t);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public void save(T t) {
		Tenant tenant = getTenant();
		if (tenant != null) {
			BeanUtil.setPropertySilent(t, TENANT, tenant);
		}
		
		repository.save(t);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public void delete(T t) {
		// fetch pre-image and save asynchronously.
		repository.delete(t);

	}
	
	@SuppressWarnings("unchecked")
	@Override
	public T findOne(Id id) {
		return (T) repository.findOne(id);
	}

	protected Tenant getTenant() {
		return SecurityUtil.getTenant();
	}

	@PostConstruct
	private void init() {
		initInternal();
	}

	protected abstract void initInternal();

	

}
